﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Net_SCADA.Siemens;

namespace Net_SCADA
{
    public delegate void BoxSerialChanged(ProcessBox pBox);
    public class ProcessBox
    {
        public event BoxSerialChanged OnBoxSerialChanged;
        private int _boxserial;
        private string _DBIndex  = "BD100";
        private int year=2000;//2000年
        private int monthday=102;//1月2日
        public hsl_Client hsl_Box { get; private set; }//hsl的client
        public DateTime[] KeyTime { get; private set; } = new DateTime[35];//各个关键时间点
        public DateTime LoadTime { get; private set; } = new DateTime(2020, 1, 1, 0, 0, 0);//box中的实际最小时间

        public int BoxMark { get; set; }//box上位机给定标记
        public float QuenchMoveinTime { get; set; } = 0;//淬火转移时间
        public float BoxWeight { get; set; } = 0;//box重量
        public int ErrorCode { get; set; } = 0;//异常代码
        public int LampCode { get; set; } = 0;//指示灯代码。上位机可以设定
        public int LoadIndex { get; set; } = 0;//标记有无物料，=0时没有物料，>0时有物料
        public bool isKeyPostion { get; set; }//是否关键位置
        public int LoadSerial { get { return BoxSerial * 10000 + BoxMark; } }//box的标识，程序辨别使用
        public StringBuilder BatchSerial { get; set; } = new StringBuilder();//批次号
        public StringBuilder OtherInfo { get { return new StringBuilder().Append(BoxSerial).Append(",").Append(BoxMark).Append(",").Append(year).Append(",").Append(monthday) ; } }//显示用参数

        //料盘编号
        public int BoxSerial    
        {
            get => _boxserial;
            set => CheckForChange(value);
        }
        public int PostionIndex { get; set; } = 0;
        public string DBIndex { get => _DBIndex; set => _DBIndex = value; }

        public ProcessBox(int posIndex,string dbindex)
        {
            PostionIndex = posIndex;
            DBIndex = dbindex;
        }

        public void SetAlarmStatusToPLC(Dictionary<int , object> alarmStatus) 
        {
            hsl_Box.RandemSetItemValues(alarmStatus);
        }

        public void initHSLClient(hsl_Server server ,string[] InterAdd)
        {
            hsl_Box = new hsl_Client(server);
            List<string> lst = new List<string>();
            for (int i = 0 ; i < InterAdd.Length ; i++)
            {
                lst.Add(DBIndex +","+ InterAdd[i]);
            }
            hsl_Box.InstallHslItems(lst);
        }
        //刷新数据
        public void FlashData()
        {
            Task.Run(()=> {
                hsl_Box.GetDataFromPLC();
                List<object> v = hsl_Box.ItemValues;
                if (v.Count > 0)
                {
                    //BoxMark = Convert.ToInt32(v[1]);
                    //LoadIndex = Convert.ToInt32(v[0]);
                    ErrorCode = Convert.ToInt32(v[4]);
                    LampCode = Convert.ToInt32(v[7]);
                    QuenchMoveinTime = Convert.ToInt32(v[5]) * 0.1f;
                    BoxWeight = Convert.ToInt32(v[10]);
                    year = Convert.ToInt32(v[8]);
                    monthday = Convert.ToInt32(v[9]);
                    for (int i = 0; i < KeyTime.Length; i++)
                    {
                        DateTime.TryParse(v[11 + i].ToString(), out KeyTime[i]);
                    }
                    BoxSerial = Convert.ToInt32(v[2]);//最后搞boxserial
                }

            }).Wait();
        }
        public bool ChangeBoxInfo(int loadindex, int boxserial,int lampvalue)
        {
            FlashData();
            if (loadindex == 0)
            {
                BoxMark =0;
                return hsl_Box.RandemSetItemValues(new Dictionary<int, object>() { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 8, 0 }, {9, 0 } });
            }
            else
            {

                if (BoxMark == 0 || BoxSerial == 0)
                {
                    //BoxMark = DateTime.Now.Hour * 100 + DateTime.Now.Minute;
                }
                else
                {
                    LoadTime = GetLoadTime();
                    if (LoadTime.Year > 2020 && LoadTime.Year != 2200)
                    {
                        DataTable dt = DBOperate.FindProcessBox(BoxSerial, BoxMark, LoadTime);
                        if (dt != null && dt.Rows.Count > 0)
                            DBOperate.ChangeBoxSerial(BoxSerial, boxserial, BoxMark, LoadTime);
                    }

                }
                return hsl_Box.RandemSetItemValues(new Dictionary<int, object>() { { 0, loadindex }, { 2, boxserial }, { 7, lampvalue } });
            }
        }
        //在特定的情况下刷新
        public void SaveBoxInfo()
        {
            Dictionary<string,string> v = new Dictionary<string , string>();
            if (BoxSerial == 0) return;
            for (int i = 0 ; i < KeyTime.Length ; i++)
            {
                v.Add("keytime" + i , KeyTime[i].Year<2021?"-":KeyTime[i].ToString("yyyy-MM-dd HH:mm:ss"));
            }
            v.Add("errorcode" , ErrorCode.ToString());
            if(QuenchMoveinTime>0) v.Add("quenchmoveintime" , QuenchMoveinTime.ToString());
            if(BoxWeight>0) v.Add("weight" , BoxWeight.ToString());
            LoadTime = GetLoadTime();
            if (LoadTime.Year > 2020 && LoadTime.Year != 2200)
                DBOperate.SaveProcessBoxInfo(BoxSerial, BoxMark, LoadTime, v);
        }
        private DateTime GetLoadTime()
        {
            DateTime d = new DateTime(2200, 1, 1, 0, 0, 0);
            for (int i = 0; i < KeyTime.Length; i++)
            {
                if (KeyTime[i].Year > 2020)//判断是否是合理的时间
                {
                    if (KeyTime[i] < d)
                        d = KeyTime[i];
                }
            }
            return d;
        }
        private bool SendBoxMark()//由上位机给的一个标记，基本上使用的小时和分钟、
        {

            DateTime d = GetLoadTime();
            if (d.Year == 2200) return false;
            year = d.Year;
            monthday = d.Month * 100 + d.Day;
            BoxMark = d.Hour * 100 + d.Minute;
            LoadTime = d;
            if (NetLine.isBatchStart && NetLine.Batchs.Count > 0)
                BatchSerial = new StringBuilder().Append(NetLine.Batchs.Last().BatchSerial);
            return hsl_Box.RandemSetItemValues(new Dictionary<int, object>() {
                { 1,BoxMark },
                { 8,year},
                { 9,monthday}
            });
        }

        private void CheckForChange(int boxserial)
        {
            if (_boxserial != boxserial)
            {
                _boxserial = boxserial;
                FlashData();
                if (LoadIndex > 0)
                {
                    if (BoxMark == 0)
                        SendBoxMark();
                }
                if (OnBoxSerialChanged != null)
                    OnBoxSerialChanged.Invoke(this);
            }
        }
    }
}
